<?php
declare (strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin Model
 */
class Logs extends Model
{
    //
    protected $json = ['content'];

    public function user()
    {
        return $this->hasOne(Users::class, 'id', 'user_id');
    }

    public function getLevelTextAttr($val, $data)
    {
        $text = [0 => 'info', 1 => 'notice', 2 => 'warning', 3 => 'error'];
        return $text[$data['level']];
    }

    public static function write($content, $level = 0)
    {
        $user = request()->user;
        $content = json_encode($content);
        Logs::create([
            'user_id' => $user->id,
            'content' => $content,
            'ip' => request()->ip(),
            'level' => $level
        ]);
    }

    public static function info($content)
    {
        $user = request()->user;
        $content = json_encode($content);
        Logs::create([
            'user_id' => $user->id,
            'content' => $content,
            'ip' => request()->ip(),
            'level' => 0
        ]);
    }

    public static function notice($content)
    {
        $user = request()->user;
        $content = json_encode($content);
        Logs::create([
            'user_id' => $user->id,
            'content' => $content,
            'ip' => request()->ip(),
            'level' => 1
        ]);
    }

    public static function warning($content)
    {
        $user = request()->user;
        $content = json_encode($content);
        Logs::create([
            'user_id' => $user->id,
            'content' => $content,
            'ip' => request()->ip(),
            'level' => 2
        ]);
    }

    public static function error($content)
    {
        $user = request()->user;
        $content = json_encode($content);
        Logs::create([
            'user_id' => $user->id,
            'content' => $content,
            'ip' => request()->ip(),
            'level' => 3
        ]);
    }
}
